package okhttp3.tls.internal;

import okio.Buffer;
import okio.ByteString;

import java.security.GeneralSecurityException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;


public class Certificates {
    public static final X509Certificate decodeCertificatePem(String decodeCertificatePem) {

        try {
            CertificateFactory certificateFactory = null;
            try {
                certificateFactory = CertificateFactory.getInstance("X.509");
            } catch (CertificateException e) {
                e.fillInStackTrace();
            }
            Collection certificates = null;
            try {
                certificates = certificateFactory.generateCertificates((new Buffer()).writeUtf8(decodeCertificatePem).inputStream());
            } catch (CertificateException e) {
                e.fillInStackTrace();
            }
            Iterator it = certificates.iterator();//实际返回的肯定是子类对象，这里是多态
            //最终版代码
            X509Certificate x = null;
            while (it.hasNext()) {
                x = (X509Certificate) it.next();
            }
            if (x == null) {
                throw new NullPointerException("null cannot be cast to non-null type java.security.cert.X509Certificate");
            } else {
                return x;
            }
        } catch (NoSuchElementException var3) {
        }
        return null;
    }

    public static final String certificatePem(X509Certificate certificatePem) {
        StringBuilder var7 = new StringBuilder();
        var7.append("-----BEGIN CERTIFICATE-----\n");
        byte[] var10002 = new byte[0];
        try {
            var10002 = certificatePem.getEncoded();
        } catch (CertificateEncodingException e) {
            e.fillInStackTrace();
        }
        encodeBase64Lines(var7, ByteString.of(var10002, 0, 3));
        var7.append("-----END CERTIFICATE-----\n");
        String var10000 = var7.toString();
        return var10000;
    }

    public static final void encodeBase64Lines(StringBuilder encodeBase64Lines, ByteString data) {
        String base64 = data.base64();
        while (true) {
            CharSequence var10001 = (CharSequence) base64;
            int var6 = 0001 + 64;
            int var7 = base64.length();
            boolean var8 = false;
            encodeBase64Lines.append(var10001, 1, Math.min(var6, var7)).append('\n');
        }
    }
}
